<?php

declare(strict_types=1);

namespace app\api\controller;

use app\api\controller\Base;
use app\common\model\User;
use app\common\model\UserAccount;
use \think\Request;
use think\facade\Db;
use app\common\model\ProfitDraw;
use app\common\model\UserLoginIp;
use think\facade\Log;

class Login extends Base
{
    /**
     * 微信授权
     */
    public function login()
    {

        $code = request()->param("code", '');
        if (empty($code)) {
            return $this->renderError('请求参数错误');
        }
        $click_id = request()->header('clickid');
        $wxServer = new \app\common\server\Wx($this->app);
        $openid = $wxServer->getOpenid($code);
        // file_put_contents('./jjj.txt', $openid);
        // writelog('openid', $openid);
        $user = User::getInfo(['openid' => $openid]);
        // return $this->renderSuccess("登录成功", $user);
        if (!empty($user)) {
            if ($user['click_id'] != $click_id) {
                $res[] = User::where(['id' => $user['id']])->update(['click_id' => $click_id]);
            }
            #token时间戳
            $time = time();
            #token字符串
            $token_num = getRandStr(10);
            #加密token
            $account_token = user_md5($user['id'] . $token_num . $time);
            #更新账号信息
            $last_login_ip1 = request()->ip();
            $result = $this->ip_location($last_login_ip1);
            $ip_province = '';
            $ip_city = '';
            $ip_adcode = '';
            if ($result) {
                $ip_province = $result['province'];
                $ip_city = $result['city'];
                $ip_adcode = $result['adcode'];
                if (empty($ip_province) || empty($ip_city)) {
                    $url = 'https://api.ip138.com/ip/?ip=' . $last_login_ip1;
                    $header = array('token:85a4f162c5f1d60c9f98aa03a8c4ea03');
                    $res = getData($url, $header);
                    $res = json_decode($res, true);
                    if ($res['ret'] == 'ok') {
                        $ip_province = $res['data']['1'];
                        $ip_city = $res['data']['2'] . $res['data']['3'];
                        $ip_adcode = $res['data']['5'];
                    }
                }
            } else {
                $url = 'https://api.ip138.com/ip/?ip=' . $last_login_ip1;
                $header = array('token:85a4f162c5f1d60c9f98aa03a8c4ea03');
                $res = getData($url, $header);
                $res = json_decode($res, true);
                if ($res['ret'] == 'ok') {
                    $ip_province = $res['data']['1'];
                    $ip_city = $res['data']['2'] . $res['data']['3'];
                    $ip_adcode = $res['data']['5'];
                }
            }

            $user_account = UserAccount::where(['user_id' => $user['id']])->find();
            if ($user_account) {
                $res[] = UserAccount::where(['user_id' => $user['id']])->update([
                    'account_token' => $account_token,
                    'token_num' => $token_num,
                    'token_time' => $time,
                    'last_login_time' => $time,
                    'last_login_ip' => ip2long(request()->ip()),
                    'last_login_ip1' => $last_login_ip1,
                    'ip_adcode' => $ip_adcode,
                    'ip_province' => $ip_province,
                    'ip_city' => $ip_city,
                ]);
            } else {
                $res[] = UserAccount::insert([
                    'user_id' => $user['id'],
                    'account_token' => $account_token,
                    'token_num' => $token_num,
                    'token_time' => $time,
                    'last_login_time' => $time,
                    'last_login_ip' => ip2long(request()->ip()),
                    'last_login_ip1' => $last_login_ip1,
                    'ip_adcode' => $ip_adcode,
                    'ip_province' => $ip_province,
                    'ip_city' => $ip_city,
                ]);
            }

            #记录登录日志
            $res[] = UserLoginIp::insert([
                'user_id' => $user['id'],
                'last_login_time' => $time,
                'last_login_ip' => ip2long(request()->ip()),
                'last_login_ip1' => $last_login_ip1,
                'ip_adcode' => $ip_adcode,
                'ip_province' => $ip_province,
                'ip_city' => $ip_city,

            ]);
            return $this->renderSuccess("登录成功", $account_token);
        } else {
            $nickname = request()->param('nickname', '');
            $headimg = request()->param('headimg', '');
            if (!$nickname || !$headimg) {
                return $this->renderError('请求参数错误!');
            }
            $pid = 0;
            $pid_pid = request()->param('pid', 0);
            if ($pid_pid) {
                $pid_info = User::where('id', '=', $pid_pid)->value("id");
                if ($pid_info) {
                    log::info("获取推荐人id" . $pid_info);
                    $pid = $pid_info;
                }
            }

            Db::startTrans();

            $res[] = $user_id = User::insertGetId([
                'openid' => $openid,
                'nickname' => $nickname,
                'headimg' => $headimg,
                'pid' => $pid,
                'addtime' => time(),
                'click_id' => $click_id
            ]);
            $time = time();
            #token字符串
            $token_num = getRandStr(10);
            #加密token
            $account_token = user_md5($user_id . $token_num . $time);
            #更新账号信息
            $last_login_ip1 = request()->ip();
            $result = $this->ip_location($last_login_ip1);
            $ip_province = '';
            $ip_city = '';
            $ip_adcode = '';
            if ($result) {
                $ip_province = $result['province'];
                $ip_city = $result['city'];
                $ip_adcode = $result['adcode'];
            } else {
                $url = 'https://api.ip138.com/ip/?ip=' . $last_login_ip1;
                $header = array('token:85a4f162c5f1d60c9f98aa03a8c4ea03');
                $res = getData($url, $header);
                $res = json_decode($res, true);
                if ($res['ret'] == 'ok') {
                    $ip_province = $res['data']['1'];
                    $ip_city = $res['data']['2'] . $res['data']['3'];
                    $ip_adcode = $res['data']['5'];
                }
            }
            $res[] = UserAccount::insert([
                'user_id' => $user_id,
                'account_token' => $account_token,
                'token_num' => $token_num,
                'token_time' => $time,
                'last_login_time' => $time,
                'last_login_ip' => ip2long(request()->ip()),
                'last_login_ip1' => $last_login_ip1,
                'ip_adcode' => $ip_adcode,
                'ip_province' => $ip_province,
                'ip_city' => $ip_city,
            ]);
            #记录登录日志
            $res[] = UserLoginIp::insert([
                'user_id' => $user_id,
                'last_login_time' => $time,
                'last_login_ip' => ip2long(request()->ip()),
                'last_login_ip1' => $last_login_ip1,
                'ip_adcode' => $ip_adcode,
                'ip_province' => $ip_province,
                'ip_city' => $ip_city,

            ]);
            #推荐成功之后获取一张抽奖券
            #配置
            $rule = getConfig('base');
            $draw_people_num = $rule['draw_people_num'];
            if (!empty($pid)) {
                $num = 0;
                $num = ProfitDraw::where(['type' => 5, 'user_id' => $pid, 'share_uid' => $user_id])->count();
                if (bccomp("$num", "$draw_people_num") < 0) {
                    #可以获得一张抽奖券
                    $res[] = User::changeDraw($pid, 1, 5, '获得一张抽奖券', $user_id);
                }
            }
            if (resCheck($res)) {
                Db::commit();
                return $this->renderSuccess("登录成功", $account_token);
            } else {
                Db::rollback();
                return $this->renderError("登录失败");
            }
        }
    }

    public function ip_location($last_login_ip)
    {
        if ($last_login_ip) {
            $url = "https://restapi.amap.com/v3/ip?key=6a46ad822120e393956e89d498e8c40b&ip=" . "$last_login_ip" . "";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            $result = curl_exec($ch);
            curl_close($ch);

            $result = json_decode($result, true);
            if ($result['status'] == '1') {
                return $result;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    //     public function get_ip_city($ip){


    //         $ip = '117.25.13.123';
    //         $datatype = 'txt';
    //         $url = 'https://api.ip138.com/ip/?ip='.$ip.'&datatype='.$datatype;
    //         $header = array('token:00d5cb1fac5dc5cbfe2ff218292a2dfd33');
    //         echo getData($url,$header);  





    //       $ch = curl_init();
    //       $url = "https://www.ip138.com/iplookup.php?ip=123.14.94.16&action=2";
    //       //$url = 'https://whois.pconline.com.cn/ipJson.jsp?ip=' . $ip;
    //         //用curl发送接收数据
    //     curl_setopt($ch, CURLOPT_URL, $url);
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //     //请求为https
    //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //     $location = curl_exec($ch);
    //     curl_close($ch);
    //     //转码
    //       var_dump($location);
    //     exit;
    //     $location = mb_convert_encoding($location, 'utf-8', 'GB2312');
    //   var_dump($location);

    //     //var_dump($location);
    //     //截取{}中的字符串
    //     $location = substr($location, strlen('({') + strpos($location, '({'), (strlen($location) - strpos($location, '})')) * (-1));
    //     //将截取的字符串$location中的‘，’替换成‘&’   将字符串中的‘：‘替换成‘=’
    //     $location = str_replace('"', "", str_replace(":", "=", str_replace(",", "&", $location)));
    //     //php内置函数，将处理成类似于url参数的格式的字符串  转换成数组
    //     parse_str($location, $ip_location);
    //     // return $ip_location['addr']; # 返回字符串
    //     return $ip_location; # 返回数组
    //     }


    public function aa()
    {
        $ip = '117.25.13.1231';
        $url = 'https://api.ip138.com/ip/?ip=' . $ip;
        $header = array('token:85a4f162c5f1d60c9f98aa03a8c4ea03');
        $res = getData($url, $header);
        $res = json_decode($res, true);
        if ($res['ret'] == 'ok') {
            $ip_province = $res['data']['0'] . $res['data']['1'];
            $ip_city = $res['data']['2'] . $res['data']['3'];
            $ip_adcode = $res['data']['5'];
        }
    }

    /**
     * 绑定手机号
     */
    public function login_bind_mobile()
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $code = request()->param("code", '');
        $wxServer = new \app\common\server\Wx($this->app);
        $mobile = $wxServer->getMobile($code);
        Db::startTrans();
        $res = [];
        $user_mobile = User::where(['mobile' => $mobile])->find();
        if (!empty($user_mobile)) {
            $old_user_account = UserAccount::where(['user_id' => $user_id])->find();
            // // 修改openid
            $res[] = User::where(['id' => $user_mobile['id']])
                ->update([
                    'openid' => $user['openid'],
                    'nickname' => $user['nickname'],
                    'headimg' => $user['headimg'],
                ]);

            $res[] = User::where(['id' => $user_id])->delete();
            $res[] = UserAccount::where(['user_id' => $user_id])->delete();

            $where = [];
            $where[] = ['user_id', '=', $user_mobile['id']];
            $data = [
                'account_token' => $old_user_account['account_token'],
                'token_num' => $old_user_account['token_num'],
                'token_time' => $old_user_account['token_time'],
                'last_login_time' => $old_user_account['last_login_time'],
                'last_login_ip' => $old_user_account['last_login_ip'],
            ];
            $res[] = Db::name('user_account')
                ->where($where)
                ->update($data);
        } else {
            $res[] = User::where(['id' => $user['id']])->update([
                'mobile' => $mobile,
                'update_time' => time(),
            ]);
        }
        if (resCheck($res)) {
            Db::commit();
            return $this->renderSuccess("绑定成功2");
        } else {
            Db::rollback();
            return $this->renderSuccess("绑定成功33");
        }
    }

    public function test()
    {
        $account_token['token'] = "77f6358084be8d5545747911e7f9d5ad5644a114";
        $account_token['logintype'] = "2";
        return $this->renderSuccess("登录成功", $account_token);
    }

    public function test1()
    {
        $share_image = getConfig("base")['share_image'];
        $public_path = dirname($_SERVER['SCRIPT_FILENAME']);
        $poster_bg = $public_path . $share_image;
        var_dump($poster_bg);
        // $rule = getConfig('base');
        //     $draw_people_num = $rule['draw_people_num'];
        //     $user_id = 31;
        //     $pid = 24;
        //     if(!empty($pid)){
        //         $num = 0;
        //         $num = ProfitDraw::where(['type'=>5,'user_id'=>$pid])->count();
        //         if(bccomp("$num","$draw_people_num") < 0){
        //             #可以获得一张抽奖券
        //              $res= User::changeDraw($pid, 1,5 , '获得一张抽奖券',$user_id);
        //              var_dump($res);
        //         }

        //     }
        //     log::info($res);
    }
}
